<template>
    <div style="margin: 4px 4px 0px;">
        <div class="ant-row" style="margin-left: -12px; margin-right: -12px;">
            <div class="ant-col ant-col-md-24" style="padding-left: 12px; padding-right: 12px;">
                <div class="ant-card">
                    <div class="ant-card-body">
                        <div class="table-page-search-wrapper" style="margin-left: 20px;">
                            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                                <el-form-item label="单据编号：">
                                    <el-input v-model="menu.number" placeholder="请输入单据编号" clearable class="input"
                                        style="width: 280px; margin-left: 10px;" />
                                </el-form-item>
                                <el-form-item label="商品信息：">
                                    <el-input v-model="menu.standard" placeholder="请输入条码、名称、规格、型号、颜色" clearable
                                        class="input" style="width: 280px; margin-left: 10px;" />
                                </el-form-item>
                                <el-form-item label="单据日期：">
                                    <el-date-picker type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                                        format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                                        time-format="A hh:mm:ss" style="width: 280px; margin-left: 10px;"
                                        v-model="menu.createTime" />
                                </el-form-item>


                                <el-form-item>
                                    <el-button type="primary" @click="loadMenus">查询</el-button>
                                    <el-button @click="onReset">重置</el-button>
                                    <a style="margin-left: 8px; color: #1890ff;" @click="toggle">
                                        {{ expanded ? '收起' : '展开' }}
                                        <i class="anticon anticon-down" :class="{ 'rotated': expanded }">
                                            <svg viewBox="64 64 896 896" data-icon="down" width="1em" height="1em"
                                                fill="currentColor" aria-hidden="true" focusable="false"
                                                :style="{ transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)' }">
                                                <path
                                                    d="M884 256h-75c-5.1 0-9.9 2.5-12.9 6.6L512 654.2 227.9 262.6c-3-4.1-7.8-6.6-12.9-6.6h-75c-6.5 0-10.3 7.4-6.5 12.7l352.6 486.1c12.8 17.6 39 17.6 51.7 0l352.6-486.1c3.9-5.3.1-12.7-6.4-12.7z">
                                                </path>
                                            </svg>
                                        </i>
                                    </a>
                                </el-form-item>
                                <transition name="fade">
                                    <div v-if="expanded" class="additional-content">


                                        <el-form-item label="客户：">
                                            <el-select v-model="menu.supName" clearable
                                                style="width: 307px; margin-left: 10px;" placeholder="请选择客户">
                                                <el-option v-for="customer in customers" :key="customer.id"
                                                    :label="customer.supName" :value="customer.supName" />
                                            </el-select>


                                        </el-form-item>
                                        <el-form-item label="仓库名称：">
                                            <el-select v-model="menu.dname" clearable
                                                style="width: 280px; margin-left: 10px;" placeholder="请选择仓库">
                                                <el-option v-for="depot in depots" :key="depot.id" :label="depot.name"
                                                    :value="depot.name" />
                                            </el-select>


                                        </el-form-item>
                                        <el-form-item label="操作员：">
                                            <el-select v-model="menu.username" clearable
                                                style="width: 313px; margin-left: 10px;" placeholder="请选择操作员">
                                                <el-option v-for="user in users" :key="user.id" :label="user.username"
                                                    :value="user.username" />
                                            </el-select>


                                        </el-form-item>
                                        <el-form-item label="关联订单：">
                                            <el-input placeholder="请输入关联订单">

                                            </el-input>


                                        </el-form-item>
                                        <el-form-item label="结算账户：">
                                            <el-select v-model="menu.accountname" clearable
                                                style="width: 280px; margin-left: 10px;" placeholder="请选择结算账户">
                                                <el-option v-for="account in accounts" :key="account.id"
                                                    :label="account.name" :value="account.name" />
                                            </el-select>


                                        </el-form-item>
                                        <el-form-item label="有无欠款：">
                                            <el-select v-model="menu.debt" clearable
                                                style="width: 280px; margin-left: 10px;" placeholder="选择有无欠款">
                                                <el-option v-for="debt in debtData" :key="debt.name" :label="debt.name"
                                                    :value="debt.name" />
                                            </el-select>


                                        </el-form-item>
                                        <el-form-item label="单据状态：">
                                            <el-select v-model="menu.status" clearable
                                                style="width: 300px; margin-left: 10px;" placeholder="请选择单据状态">
                                                <el-option v-for="status in stausData" :key="status.status"
                                                    :label="status.value" :value="status.status" />

                                            </el-select>


                                        </el-form-item>
                                        <el-form-item label="单据备注：">
                                            <el-input placeholder="请输入关联订单">

                                            </el-input>


                                        </el-form-item>
                                    </div>
                                </transition>
                            </el-form>
                        </div>

                        <div class="table-wapper-box" style="margin-left: 20px;">
                            <div class="table-operator" style="margin-top: 5px;">
                                <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;"
                                    plain v-perm:sale:sale_in:ininsert="insert">
                                    <el-icon class="el-icon-left">
                                        <Plus />
                                    </el-icon>
                                    <span>新增</span>
                                </el-button>
                                <el-dropdown>
                                    <el-button class="ant-btn ant-dropdown-trigger">
                                        批量操作<el-icon class="el-icon--right">
                                            <ArrowDown />
                                        </el-icon>
                                    </el-button>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <template v-for="item in strBtn">
                                                <template v-if="item === '编辑'">
                                                    <el-dropdown-item @click="deleteSelected">
                                                        <el-icon>
                                                            <Delete />
                                                        </el-icon>
                                                        <span>删除</span>
                                                    </el-dropdown-item>
                                                </template>
                                                <template v-else-if="item === '审核'">
                                                    <el-dropdown-item @click="updateOrderStatus1">
                                                        <el-icon>
                                                            <Select />
                                                        </el-icon>
                                                        <span>{{ item }}</span>
                                                    </el-dropdown-item>
                                                </template>
                                                <template v-else>
                                                    <el-dropdown-item @click="updateOrderStatus2">
                                                        <el-icon>
                                                            <CircleClose />
                                                        </el-icon>
                                                        <span>{{ item }}</span>
                                                    </el-dropdown-item>
                                                </template>

                                            </template>
                                            <!-- <el-dropdown-item @click="modifyTheState(1)">
              <el-icon>
                <Select />
              </el-icon>
              <span>审核</span>
            </el-dropdown-item>
            <el-dropdown-item @click="modifyTheState(0)">
              <el-icon>
                <CircleClose />
              </el-icon>
              <span>反审核</span>
            </el-dropdown-item> -->
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                            <div class="tooltip-base-box">
                                <div class="row"
                                    style="width: 100px; margin-left: 50px; display: flex; flex-wrap: wrap;">
                                    <el-tooltip class="box-item" effect="dark" content="销售出库可以由销售订单传过来，也可以单独创建。"
                                        placement="left">
                                        <el-icon style="font-size: 22px; color: #E6E6E6;">
                                            <QuestionFilled />
                                        </el-icon>
                                    </el-tooltip>
                                </div>
                            </div>
                        </div>

                        <div>
                            <div class="ant-spin-nested-loading">
                                <div class="ant-spin-container">
                                    <div
                                        class="ant-table anr-table-scroll-position-left ant-table-layout-fixed ant-table-middle ant-table-bordered">
                                        <div class="ant-table-content">
                                            <div class="ant-table-body">
                                                <el-table :data="page.records" border stripe v-loading="loading"
                                                    element-loading-text="Loading..." :element-loading-spinner="svg"
                                                    element-loading-background="rgba(122, 122, 122, 0.1)"
                                                    @selection-change="handleSelectionChange"
                                                    style="width: 100%; max-width: 1800px;">
                                                    <el-table-column type="selection" width="80"
                                                        align="center" /><!-- 多选框 -->

                                                    <el-table-column label="操作" width="210" align="center">
                                                        <template #default="scope">
                                                            <div style="text-align: center;">
                                                                <div class="operation-buttons">
                                                                    <div class="operation-group">
                                                                        <a class="operation-link"
                                                                            @click="orderFind({ cname: '销售订单-详情', path: '/sale/sale_in/infind' }, scope.row)">查看</a>
                                                                        <a class="operation-link"
                                                                            @click="toUpdate({ cname: '编辑标题', path: '/sale/sale_in/update' }, scope.row)"v-perm:sale:sale_in:update>编辑</a>
                                                                    </div>
                                                                    <div class="operation-group">
                                                                    
                                                                        <el-popconfirm title="确认删除该项吗？"
                                                                            @confirm="remove(scope.row)">
                                                                            <template #reference>
                                                                                <a class="operation-link"
                                                                                    v-perm:sale:sale_order:sale_delete>
                                                                                    删除</a>
                                                                            </template>
                                                                        </el-popconfirm>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </template>
                                                    </el-table-column>

                                                    <el-table-column prop="createTime" label="单据日期" width="170" />
                                                    <el-table-column v-if="showIdColumn" prop="id" label="id"
                                                        width="170" />
                                                    <el-table-column prop="erpSupplier.supName" label="客户"
                                                        width="115" />
                                                    <el-table-column prop="number" label="单据编号" width="243" />
                                                    <el-table-column
                                                        prop="erpDepotItemList[0].erpMaterial.material_name"
                                                        label="商品信息" width="160" />
                                                    <el-table-column prop="erpUser.username" label="操作员" width="110" />
                                                    <el-table-column prop="erpDepotItemList[0].total_quantity"
                                                        label="数量" width="105" />
                                                    <el-table-column prop="totalPrice" label="金额合计" width="100" />
                                                    <el-table-column prop="totalPrice" label="含税金额" width="100" />
                                                    <el-table-column prop="deposit" label="收取定金" width="90"
                                                        align="center" />
                                                    <el-table-column label="状态" width="100" align="center">
                                                        <template #default="scope">
                                                            <el-tag v-if="scope.row.status == 0" type="danger"
                                                                effect="light">
                                                                未审核
                                                            </el-tag>
                                                            <el-tag v-else-if="scope.row.status == 1" type="success"
                                                                effect="light">
                                                                已审核
                                                            </el-tag>
                                                            <el-tag v-else-if="scope.row.status == 2" type="warning"
                                                                effect="light">
                                                                完成销售
                                                            </el-tag>
                                                            <el-tag v-else-if="scope.row.status == 3" type="warning"
                                                                effect="light">
                                                                部分销售
                                                            </el-tag>
                                                        </template>
                                                    </el-table-column>
                                                </el-table>

                                                <el-pagination v-model:page-size="page.size"
                                                    v-model:current-page="page.current"
                                                    @current-change="handleCurrentChange"
                                                    @size-change="handleSizeChange" :page-sizes="[2, 4, 8, 10]"
                                                    layout="total, sizes, prev, pager, next, jumper" :total="page.total"
                                                    background style="margin-top:20px;">
                                                </el-pagination>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新增弹窗 -->
        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="1550px" height="500px"
            style="margin-left: 250px;">
            <router-view @close="close" :data="data"></router-view>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref ,defineProps} from 'vue';
import request from '@/api/request';
import { ElMessage } from 'element-plus';
import router from '@/router';

const props = defineProps(['strBtn'])
let strBtn = props.strBtn

const loading = ref(false);
const visible = ref(false);
const title = ref("");
const data = ref({});
const page = ref({
    current: 1,
    size: 10,
    total: 0,
    records: []
});
const menu = ref({});
const formInline = reactive({
    region: '',
    customer: '' // 新增客户字段
});

const selectedIds = ref([]);
const customers = ref([]); // 存储客户数据

const loadCustomers = () => {
    request({
        url: '/basic/vendor/list',
        method: 'get'
    }).then(res => {

        customers.value = res.data; // 更新客户数据
    }).catch(err => {
        console.error(err);
    });
};
let stausData = [
    { status: '0', value: '未审核' },
    { status: '1', value: '已审核' },
    { status: '2', value: '完成销售' }

]


const depots = ref([]);
const loadDepot = () => {
    request({
        url: '/depot/list',
        method: 'get'
    }).then(res => {
        depots.value = res.data; // 更新仓库数据
    }).catch(err => {
        console.error(err);
    });
};
loadDepot(); // 加载仓库数据
const loadMenus = () => {
    loading.value = true;

    // 先获取表单中选择的欠款状态
    const selectedDebtStatus = menu.value.debt;

    request({
        url: '/sale/findByPageOderck',
        method: "get",
        params: {
            current: page.value.current,
            size: page.value.size,
            name: menu.value.name,
            number: menu.value.number,
            standard: menu.value.standard,
            createTime: menu.value.createTime,
            username: menu.value.username,
            status: menu.value.status,
            remark: menu.value.remark,
            supName: menu.value.supplier,
            dname: menu.value.dname,
            accountname: menu.value.accountname
        }
    }).then(res => {
        const records = res.data.records.map(record => ({
            ...record,//服务器获取的记录数组，map遍历数组，将其中的字段取出来，组成新的对象，然后返回给records数组
            debtStatus: record.debt > 0 ? '有欠款' : '无欠款'//如果大于0，则有欠款，否则无欠款
        })).filter(record => {
            //filter方法过滤数组，返回符合条件的数组
            if (selectedDebtStatus == null) return true; // 如果没有选择，则显示所有
            return record.debtStatus == selectedDebtStatus;//如果选择的欠款状态和记录的欠款状态一致，则显示，否则不显示
        });

        page.value.records = records;//把值重新赋值给page显示
        page.value.total = res.data.total;//总行数也赋值给page显示  

        setTimeout(() => {
            loading.value = false;
        }, 100);//挂载table查询每次当条件或者页码变动时都会调用loadMenus方法
    })
};




const handleSelectionChange = (val) => {
    selectedIds.value = val.map(item => item.id); // 更新选中的 ID
};

const deleteSelected = () => {
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请先选择至少一项记录');
        return;
    }

    console.log("选中的ID:", selectedIds.value);

    request.delete("/sale/delete", {
        data: selectedIds.value // 批量删除
    }).then(resp => {
        ElMessage.success('删除成功');
        loadMenus();
        selectedIds.value = []; // 清空选中的 ID
    });
};

const handleSizeChange = (val) => {
    page.value.size = val;
    page.value.current = 1;
    loadMenus();
};

const handleCurrentChange = (val) => {
    page.value.current = val;
    loadMenus();
};

const onReset = () => {
    formInline.region = '';
    formInline.customer = ''; // 重置客户选择
    menu.value = {};
    loadMenus();
};

const insert = (p) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    loadMenus();
};

const remove = (row) => {
    request.delete("/sale/deleteck/" + row.id).then(resp => {
        loadMenus();
    });
};

const expanded = ref(false);
const toggle = () => {
    expanded.value = !expanded.value;
};

const close = () => {
    visible.value = false;
};

const toUpdate = (p, row) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    data.value = row;
};
const orderFind = (p, row) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    data.value = row;
    console.log(row);

}
const Copy = (p) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
};

const updateOrderStatus1 = () => {
    console.log("选中的ID:", selectedIds.value);

    request.put("/sale/updatestatus", {
        ids: selectedIds.value,
        status: "1"
    }).then(resp => {
        ElMessage.success('状态更新成功');
        loadMenus();
    }).catch(error => {
        ElMessage.error('状态更新失败');
        console.error(error);
    });
};

const updateOrderStatus2 = () => {
    console.log("选中的ID:", selectedIds.value);

    request.put("/sale/updatestatus", {
        ids: selectedIds.value,
        status: "0"
    }).then(resp => {
        ElMessage.success('状态更新成功');
        loadMenus();
    }).catch(error => {
        ElMessage.error('状态更新失败');
        console.error(error);
    });
};

const users = ref({})
const userfin = () => {
    request({
        url: '/user/user',
        method: 'get'

    }).then(res => {
        users.value = res.data
        console.log(res)
    })
}
const accounts = ref([]); // 存储结算账户数据
const loadAccounts = () => {
    request({
        url: '/basic/account/list',
        method: 'get'
    }).then(res => {
        console.log(res);
        accounts.value = res.data; // 更新结算账户数据
    }).catch(err => {
        console.error(err);
    });
};
loadAccounts();
const debtData = [
    { name: '有欠款', value: '有欠款' },
    { name: '无欠款', value: '无欠款' }
];

// 初始化数据加载
loadCustomers(); // 加载客户数据
loadMenus(); // 加载菜单数据
userfin();//加载操作员数据
</script>

<style scoped>
.table-wapper-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-operator {
    margin-top: 20px;
}

.operation-buttons {
    display: flex;
    align-items: center;
    justify-content: center;
}

.operation-link {
    margin: 0 8px;
    color: #1890ff;
    text-decoration: none;
    cursor: pointer;
}

.ant-table {
    margin-top: 10px;
    border-radius: 4px;
    overflow: hidden;
}

.ant-table th,
.ant-table td {
    padding: 10px;
    text-align: center;
}

.ant-spin-nested-loading {
    position: relative;
}

.ant-spin-container {
    padding: 20px;
}

.ant-table-content {
    overflow-x: auto;
}

.ant-table-body tr:hover {
    background-color: #e9e9e9;
}
</style>
